package com.quasar.hpatient.module.doctor;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.doctor.DoctorBean;
import com.quasar.hpatient.module.doctor_detail.DoctorDetailActivity;
import com.quasar.hpatient.module.doctor_chat.DoctorChatActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.reactivex.Observable;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.recycler.BaseCommonAdapter;
import lib.quasar.recycler.decoration.TabDecoration;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.util.DimenUtil;
import lib.quasar.util.SpannableUtil;
import lib.quasar.widget.bar.ContactBar;
import lib.quasar.widget.bold.TextBoldView;
import okhttp3.RequestBody;

/**
 * description: 我的医生
 * created by kalu on 2018/3/19 16:14
 */
public class DoctorPresenter implements BasePresenter {

    private final ArrayList<DoctorBean> mDatas = new ArrayList<>();

    void initList(final DoctorView view, RecyclerView recycler) {

        if (null == view || null == recycler) return;

        final int[] rollRange = {0};
        final BaseCommonAdapter<DoctorBean> adapter = new BaseCommonAdapter<DoctorBean>(mDatas, R.layout.fragment_doctor_child) {

            @Override
            protected void onNext(RecyclerHolder holder, DoctorBean model, int position) {

                final int relationtype = model.getRelation_type();
                if (relationtype == 1) {
                    view.setVisibility(holder, R.id.fragment_doctor_child_sign, View.VISIBLE);
                    view.setSign(holder, R.id.fragment_doctor_child_sign, R.string.doctor_sign1, R.color.color_bg_orange);
                } else if (relationtype == 22) {
                    view.setVisibility(holder, R.id.fragment_doctor_child_sign, View.VISIBLE);
                    view.setSign(holder, R.id.fragment_doctor_child_sign, R.string.doctor_sign2, R.color.color_bg_peach);
                } else {
                    view.setVisibility(holder, R.id.fragment_doctor_child_sign, View.GONE);
                }

                final ImageView image = holder.getView(R.id.fragment_doctor_child_head);
                view.setImage(image, model.getCover(), true);
                view.setText(holder, R.id.fragment_doctor_child_name, model.getReal_name());
                view.setText(holder, R.id.fragment_doctor_child_type, model.getPosition_name());
                view.setText(holder, R.id.fragment_doctor_child_hospital, model.getHospital_name());
                SpannableUtil.append("动态：", BaseApp.getResource().getColor(R.color.color_bg_theme));
                SpannableUtil.append("发表文章《什么是器官移植呢？》发表文章《什么是器官移植呢？》");
                view.setText(holder, R.id.fragment_doctor_child_dynamics, SpannableUtil.build());

                holder.itemView.setOnClickListener(v -> {
                    final Intent intent = new Intent(BaseApp.getContext(), DoctorDetailActivity.class);
                    intent.putExtra(DoctorDetailActivity.DOCTOR_ID, model.getDoctorid());
                    view.goNext(intent);
                });

                holder.setOnClickListener(R.id.doctor_child_message, v -> {
                    //  view.toast("聊天");
                    final Intent intent = new Intent(BaseApp.getContext(), DoctorChatActivity.class);
//                    intent.putExtra("realName", model.getReal_name());
//                    intent.putExtra("doctorId", String.valueOf(model.getDoctorid()));
                    intent.putExtra(DoctorChatActivity.CHAT_NAME, model.getReal_name());
                    intent.putExtra(DoctorChatActivity.CHAT_ID, String.valueOf(model.getDoctorid()));

                    view.goNext(intent);
                });
            }

            @Override
            protected void onRoll(RecyclerView recycler, int itemHeight, int rollHeight, int rollState, int fistVisablePosition, int lastVisablePosition) {
                super.onRoll(recycler, itemHeight, rollHeight, rollState, fistVisablePosition, lastVisablePosition);

                if (mDatas.size() == 0 || fistVisablePosition >= mDatas.size()) return;
                final DoctorBean model = mDatas.get(fistVisablePosition);
                if (null == model) return;

                if (Math.abs(rollHeight - rollRange[0]) > itemHeight * 0.7f) {
                    rollRange[0] = rollHeight;
                    view.scrollBar(model.getLetter());
                }
            }
        };

        adapter.setNullView(BaseApp.getContext(), R.layout.layout_recycler_loading);
        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        view.setRecycler(recycler, adapter, manager);
    }

    void doctorList(final DoctorView view, RecyclerView recycler, ContactBar bar) {

        if (null == view || null == recycler || null == bar) return;

        final RequestBody params = createParams(null, HttpParams.DATA_TYPE_1_7);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().doctorList(params);
        request(observable, new OnModelAcceptChangeListener<List<DoctorBean>>() {

            @Override
            public void modelFail() {
                view.setListNull(recycler, R.layout.layout_recycler_fail);
            }

            @Override
            public void modelSucc(List<DoctorBean> result) {

                if (null == result || result.size() == 0) {
                    modelFail();
                    return;
                }

                mDatas.addAll(result);
                Collections.sort(mDatas);

                final ArrayList<String> list = new ArrayList<>();
                for (DoctorBean temp : mDatas) {
                    final String letter = temp.getLetter();
                    if (list.contains(letter)) continue;
                    list.add(letter);
                }
                bar.setLetter(list);
                bar.setVisibility(View.VISIBLE);

                setItemDecoration(view, recycler);
                view.refreshList(recycler);
            }
        });
    }

    void scrollRecycler(DoctorView view, String letter) {

        if (null == view || TextUtils.isEmpty(letter)) return;

        for (int i = 0; i < mDatas.size(); i++) {
            if (mDatas.get(i).getLetter().equals(letter)) {
                view.scrollRecycler(i);
                break;
            }
        }
    }

    private final void setItemDecoration(final DoctorView view, RecyclerView recycler) {

        if (null == view || null == recycler) return;

        final int height = DimenUtil.dp2px(20);
        final int margin = DimenUtil.dp2px(40);
        final int left = DimenUtil.dp2px(20);
        final float font = DimenUtil.sp2px(6.5f);

        final TabDecoration decoration = new TabDecoration() {
            @Override
            public int loadHeight(int position) {
                return height;
            }

            @Override
            public String loadName(int position) {
                final String letter = mDatas.get(position).getLetter();
                return letter;
            }

            @Override
            public View loadView(int position) {
                final TextBoldView text = new TextBoldView(BaseApp.getContext());
                text.setBackgroundColor(BaseApp.getResource().getColor(R.color.color_font_gray96));
                text.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
                text.setPadding(left, 0, 0, 0);
                RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
                text.setLayoutParams(params);
                params.rightMargin = margin;
                text.setTextSize(font);
                final String letter = mDatas.get(position).getLetter();
                text.setText(letter);
                return text;
            }
        };
        view.setItemDecoration(recycler, decoration);
    }

    @Override
    public void recycler() {
    }
}